import TSpace.*;

public class ApplicationServer
{
	protected Server myServer;
	protected Client myClient;

	protected int    serverNumber;
	protected String serverName;
	protected String serverPort;

	public ApplicationServer(int serverNumberVal, String serverNameVal, String serverPortVal)
	{
		serverNumber = serverNumberVal;
		serverName = serverNameVal;
		serverPort = serverPortVal;
	
		myServer = new Server(serverName, serverPort, serverNumber);

		// i want to observe!
		myServer.getTupleImplementation().setObserver(this);

		System.out.println("Server initialized!");

		connectClient();
		
		if (myClient != null)
		{
			System.out.println("Client connected, sync'ing...");
			myServer.update(myClient.readAll());
			System.out.println("Server sync'ed succesfully!");
		}
		else
			System.out.println("Error connecting, not sync'ing...");
	}

	public void connectClient()
	{
		myClient = new Client(serverName, serverPort, (serverNumber == 1 ? 2 : 1));

		try { myClient.ping(); }
		catch (Exception e) { myClient = null; };
	}
		
	public void write(TSpace.TupleRequest aTupleRequest)
	{
		if (myClient == null)
			connectClient();

		if (myClient != null)
		{
			try
			{
				myClient.getTupleSpace().write(aTupleRequest);
			}
			catch (Exception e)
			{
				System.out.println("Error connecting, not sync'ing...");
			}
		}
		else
			System.out.println("could NOT connect, NOT sync'ing...");
	}
	
	public void take(TSpace.TupleTemplate aTupleTemplate)
	{
		if (myClient == null)
			connectClient();

		if (myClient != null)
		{
			try
			{
				myClient.getTupleSpace().take(aTupleTemplate);
			}
			catch (Exception e)
			{
				System.out.println("Error connecting, not sync'ing...");
			}
		}
		else
			System.out.println("could NOT connect, NOT sync'ing...");
	}
	
	public void run()
	{
		myServer.run();
	}

	public static void main(String[] args)
	{
		if (args.length != 3)
			throw new RuntimeException("Invalid number of arguments");
		
		ApplicationServer server = new ApplicationServer(Integer.decode(args[0]).intValue(), args[1], args[2]);

		server.run();
	}
}

